package aimis.advice;

import org.springframework.lang.Nullable;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringValueResolver;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MyTransactionAttributeSource extends NameMatchTransactionAttributeSource {

    private final Map<String, TransactionAttribute> nameMap = new HashMap<>();
    @Nullable
    private StringValueResolver embeddedValueResolver;

    @Override
    public void addTransactionalMethod(String methodName, TransactionAttribute attr) {
        if (logger.isDebugEnabled()) {
            logger.debug("Adding transactional method [" + methodName + "] with attribute [" + attr + "]");
        }
        if (this.embeddedValueResolver != null && attr instanceof DefaultTransactionAttribute dta) {
            dta.resolveAttributeStrings(this.embeddedValueResolver);
        }
        this.nameMap.put(methodName, attr);
    }

    @Override
    @Nullable
    public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
        if (!ClassUtils.isUserLevelMethod(method)) {
            return null;
        }

        String methodName = method.getName();
        TransactionAttribute attr = this.nameMap.get(methodName);

        if (attr == null) {
            if (methodName.toLowerCase().contains("get") || methodName.toLowerCase().contains("find")) {
                // 只读事务
                attr = this.nameMap.get("txAttr_readonly");
            } else {
                // 事务方法
                attr = this.nameMap.get("txAttr_required");
            }
        }
        return attr;
    }


}
